<template>
	<view style="height: 100%;">
		<!-- 遮罩层 -->
		<view class="mask pay-actionsheet-mask" :class="[show?'pay-mask-show':'']"></view>
		<!-- 组件内容 -->
		<view class="bg-light fixed-bottom pay-actionsheet" :class="[show?'pay-actionsheet-show':'']">
			<view class="h2 text-muted" style="position: absolute;top: 0; right: 20rpx;" @tap="handleClose()">×</view>
			<view class="font-weight-bold text-center pt-5">
				<text class="font-lg">￥</text><text class="h2">{{amount}}</text>
			</view>
			<view class="text-center pb-5">
				<text class="font">待支付</text>
			</view>
			<view class="text-center py-5">
				<text class="font-lg font-weight-bold">请选择支付方式</text>
			</view>
			<!-- 支付方式 -->
			<radio-group class="pt-3" @change="select">
				<label v-for="(item,index) in way" :key="index" style="position: relative;"
					class="mx-4 mt-2 bg-white p-3 flex align-center rounded-lg">
					<image :src="Domain_ICON + item.icon" class="rounded" style="width: 35rpx;height: 35rpx;" mode=""></image>
					<text class="font-md ml-2 font-weight-bold">{{item.value}}</text>
					<radio :value="item.value" style="transform:scale(0.7); position: absolute; right: 20rpx;" :checked="item.select" />
				</label>
			</radio-group>
			<picker v-if="payway=='储值卡'" @change="PickerChange" class="font" :range="card" range-key="Name">
				<view v-if="prepayment_card" class="flex flex-column ml-2">
					<text class="font ">卡号:{{prepayment_card.Prepayment_Card_Scheme_Name}}</text>
					<text class="font my-2">卡名：{{prepayment_card.Prepayment_Card_SerialNumber}}</text>
					<text class="font ">剩余金额：{{prepayment_card.Amount}}元</text>
				</view>
				<view v-else class="w-100 flex justify-center">
					<text class="font font-weight-bold mt-5">请选择储值卡</text>
				</view>
			</picker>
			<view class="px-4 py-2 fixed-bottom ">
				<view class="bg-info rounded text-center py-3 text-white font-weight-bold font" @click="submit()"
					hover-class="bg-hover-info" :hover-stay-time="150">{{payway}}￥{{amount}}</view>
			</view>
		</view>
	</view>
</template>

<script>
	const app = getApp()
	import {NowTime} from '@/static/js/DateUtil.js'
	import {accAdd} from '@/static/js/GeneralUtil.js'
	import {getAddAction} from '@/api/global.js'
	import {setSalesOrderAction,WXWeChatDefrayAction,getprepaymentCardSalesAction} from '@/api/WeChat.js'
	export default {
		data() {
			return {
				loading: false ,//节流
				payway:'微信支付',//支付方式
				balance:'',//用户余额
				Domain_ICON: app.globalData.Domain_ICON, //全局变量域名
				prepayment_card:null,
				card:[],
				first:true,
			}
		},
		props: {
			show: { //显示支付方式
				type: Boolean,
				default: false
			},
			amount: { //总计金额
				type: null,
				default: ""
			},
			sales_order: { //销售订单
				type: Object,
				default: function() {
					return {}
				}
			},
			Article_Name:{//商品名字
				type:Array,
				default:[]
			},
			way: { //支付方式
				type: Array,
				default: function() {
					return [{
						icon: '/WXlogo.png',
						value: '微信支付',
						select: true
					},
					// {
					// 	icon: '/Balancepay.png',
					// 	value: '余额支付',
					// 	select: false
					// },
					{
						icon: '/Balancepay.png',
						value: '储值卡',
						select: false
					}]
				}
			},
		},
		methods: {
			handleClose() { //关闭
				this.$emit('Close');
			},
			//选中的支付方式
			async select(e){
				this.payway = e.detail.value
				if(this.payway=='储值卡'&&this.first){
					this.first = false;
					const res = await getprepaymentCardSalesAction({
						Enterprise_Info_SerialNumber:app.globalData.enterprise,
						Open_ID:app.globalData.openid,
						Article_SerialNumber:this.sales_order.Children.sales_order_detail[0].Article_SerialNumber
					})
					if(res.Status == 'success'){
						this.card = res.Data
						this.card.forEach(item=>{
							item.Name = item.Prepayment_Card_Scheme_Name + '(剩余金额：'+accAdd(item.Prepayment_Balance,item.Gift_Balance)+'元)'
							item.Amount = accAdd(item.Prepayment_Balance,item.Gift_Balance)
						})
						return
					}
					this.first = true;
				}
			},
			getData(Sales_Order_SerialNumber){ //查询余额
			    var _this = this
				uni.request({
					url:app.globalData.Domain_Name+"/WXMemberAccountInfoIDAction",
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: "POST",
					data: {
						Member_SerialNumber: app.globalData.memberInfo.Member_SerialNumber,
					},
					success: (res) => {
						this.balance = _this.accAdd(res.data[0].Prepayment_Balance,res.data[0].Gift_Balance)
						console.log(this.balance)
						if(this.balance=='0'){
							uni.hideLoading()
							uni.showModal({
								title:'余额不足!',
								content:`当前余额数为${_this.balance}`,
								cancelText:'取消支付',
								confirmText:'微信支付',
								success: function (res) {
									if(res.cancel){
										uni.showToast({
											title:'已取消',
											icon:'none'
										})
									}else if(res.confirm){
										uni.request({//微信支付
											header: {
												'Content-Type': 'application/x-www-form-urlencoded'
											},
											url: app.globalData.Domain_Name + '/WXWeChatDefrayAction',
											method: "POST",
											data: {
												Sales_Order_SerialNumber,
												Collection_Type:"微信支付",
											},
											success: (res) => {
												let appId = res.data.sdk_appid;
												let timeStamp = res.data.sdk_timestamp+'';
												let nonceStr = res.data.sdk_noncestr;
												let packageX = res.data.sdk_package;
												let signType = res.data.sdk_signtype;
												let paySign = res.data.sdk_paysign;
												console.log(res.data);
												if (res.data.result_msg == "SUCCESS") {
													uni.hideLoading();
													uni.requestPayment({
														provider: 'wxpay',
														appId: appId,
														timeStamp: timeStamp,
														nonceStr: nonceStr,
														package: packageX,
														signType: signType,
														paySign: paySign,
														success: function(res) {
															uni.showToast({
																title: '支付成功！',
																icon: 'success',
																success() {
																	uni.navigateTo({
																		url:`/pages/paycomplete/paycomplete?price=${_this.amount}`
																	})
																}
															})
														},
														fail: function(err) {
															console.log(err);
															uni.showToast({
																title: '已取消！',
																icon: 'error'
															})
														},
														//调起支付后打开懒加载
														complete: () => {
															_this.loading = false
															uni.hideLoading();
														}
													})
												} else {
													_this.loading = false
													uni.hideLoading();
													uni.showToast({
														title: '提交失败，请重试！',
														icon: 'error'
													})
												}
											},
										})
									}
								}
							})
						}else{
							//判断余额是否大于销售价格
							if(_this.balance>=_this.amount){
								uni.request({//
									header: {
										'Content-Type': 'application/x-www-form-urlencoded'
									},
									url: app.globalData.Domain_Name + '/WXWeChatDefrayAction',
									method: "POST",
									data: {
										Sales_Order_SerialNumber,
										Collection_Type:"储值账户",
									},
									success: (res) => {
										console.log(res.data)
										if(res.data.Status=='success'){
											uni.showToast({
												title: '支付成功！',
												icon: 'success',
												success() {
													uni.navigateTo({
														url:`/pages/paycomplete/paycomplete?price=${_this.amount}`
													})
												}
											})
										}else{
											uni.showToast({
												title:'系统繁忙稍后重试',
												icon:'fail'
											})
										}
									},
								})
							}else{
								uni.hideLoading()
								uni.showModal({
									title:'余额不足!',
									content:`当前余额数为${_this.balance},
									(该微信支付优先扣除不足的余额)`,
									cancelText:'取消支付',
									confirmText:'微信支付',
									success:function(res){
										if(res.cancel){
											uni.showToast({
												title:'已取消',
												icon:'success'
											})
										}else if(res.confirm){
											uni.showLoading({
												title:'提交中...',
											})
											uni.request({//
												header: {
													'Content-Type': 'application/x-www-form-urlencoded'
												},
												url: app.globalData.Domain_Name + '/WXWeChatDefrayAction',
												method: "POST",
												data: {
													Data: JSON.stringify({
														WeChatPay:_this.accAdd(_this.amount,-_this.balance),
														BalancePay:_this.balance
													}),
													Sales_Order_SerialNumber,
													Collection_Type:"储值账户+微信支付"
												},
												success: (res) => {
													let appId = res.data.sdk_appid;
													let timeStamp = res.data.sdk_timestamp+'';
													let nonceStr = res.data.sdk_noncestr;
													let packageX = res.data.sdk_package;
													let signType = res.data.sdk_signtype;
													let paySign = res.data.sdk_paysign;
													console.log(res.data);
													if (res.data.result_msg == "SUCCESS") {
														uni.hideLoading();
														uni.requestPayment({
															provider: 'wxpay',
															appId: appId,
															timeStamp: timeStamp,
															nonceStr: nonceStr,
															package: packageX,
															signType: signType,
															paySign: paySign,
															success: function(res) {
																uni.hideLoading()
																uni.showToast({
																	title: '支付成功！',
																	icon: 'success',
																	success() {
																		uni.navigateTo({
																			url:`/pages/paycomplete/paycomplete?price=${_this.amount}`
																		})
																	}
																})
															},
															fail: function(err) {
																uni.hideLoading()
																console.log(err);
																uni.showToast({
																	title: '已取消！',
																	icon: 'error'
																})
															},
															//调起支付后打开懒加载
															complete: () => {
																_this.loading = false
																uni.hideLoading();
															}
														})
													} else {
														_this.loading = false
														uni.hideLoading();
														uni.showToast({
															title: '提交失败，请重试！',
															icon: 'error'
														})
													}
												},
											})
										}
									}
								})
							}
						}
					}
				})
			},
			PickerChange(e){//储值卡选择器
				this.prepayment_card = this.card[e.detail.value]
			},
			async submit() { //校验库存
				if (!this.loading) {
					this.loading = true
					uni.showLoading({
						title: '提交中...',
					});
					const res = await setSalesOrderAction({
						Type:'1',
						Check: JSON.stringify([{
							Sales_Unit_Price_Stock_SerialNumber: this.sales_order.Children.sales_order_detail[0].Sales_Unit_Price_Stock_SerialNumber,
							Quantity: this.sales_order.Children.sales_order_detail[0].Quantity
						}]),
						Data:JSON.stringify({sales_order:[this.sales_order]}),
						Open_ID:app.globalData.openid
					})
					//下单成功
					if(res.Status=='success'){
						//分享
						if(app.globalData.Member_Share_SerialNumber!=''){
							await getAddAction({
								Data:JSON.stringify({
									member_share_detail:[{
										Member_Share_Detail_SerialNumber:'',
										Member_Share_SerialNumber:app.globalData.Member_Share_SerialNumber,
										Open_ID:app.globalData.openid,
										Enter_Date:NowTime(),
										Sales_Order_SerialNumber:res.Data,
									}]
								}),
								Open_ID:app.globalData.openid
							})
							app.globalData.Member_Share_SerialNumber = ''
						}
						if(this.payway=='微信支付'){
							const pay = await WXWeChatDefrayAction({
								Sales_Order_SerialNumber:res.Data,
								Collection_Type:'微信支付',
								Delivery_Amount:this.sales_order.Delivery_Amount
							})
							if(pay.result_msg=="SUCCESS"){
								let appId = pay.sdk_appid;
								let timeStamp = pay.sdk_timestamp+'';
								let nonceStr = pay.sdk_noncestr;
								let packageX = pay.sdk_package;
								let signType = pay.sdk_signtype;
								let paySign = pay.sdk_paysign;
								uni.requestPayment({
									provider: 'wxpay',appId,timeStamp,nonceStr,package: packageX,signType,paySign,
									success:(res)=> {
										uni.showToast({
											title: '支付成功！',
											icon: 'success',
											success:()=> {uni.navigateTo({url:`/pages/paycomplete/paycomplete?price=${this.amount}`})}
										})
									},
									fail:(err)=> {
										uni.showToast({title: '已取消付款！',icon: 'error'})
									},
									complete: () => {//调起支付后打开懒加载
										this.loading = false
										uni.hideLoading();
									}
								})
							} else {
								uni.showToast({
									title: '提交失败，请重试！',
									icon: 'error'
								})
							}	
						} else if(this.payway=='余额支付'){
							
						} else if(this.payway=='储值卡'){
							if(this.prepayment_card&&this.prepayment_card.Amount > this.amount){
								const pay = await WXWeChatDefrayAction({
									Sales_Order_SerialNumber:res.Data,
									Collection_Type:'储值卡',
									Delivery_Amount:this.sales_order.Delivery_Amount,
									Data:JSON.stringify({Prepayment_Card_SerialNumber:this.prepayment_card.Prepayment_Card_SerialNumber})
								})
								if(res.Status == 'success'){
									uni.showToast({
										title: '支付成功！',
										icon: 'success',
										success:()=> {
											uni.navigateTo({url:`/pages/paycomplete/paycomplete?price=${this.amount}`})
										}
									})
								}
							}else{
								uni.showToast({title: '该储值卡余额不足!',icon: 'error'})
							}
						}			
					}else if(res.Status=='insufficient'){
						uni.showToast({title: '库存不足!',icon: 'error'})
					} else {
						uni.showToast({title: '提交失败，请重试！',icon: 'error'})
					}
					this.loading = false
					uni.hideLoading();
				}
			}
		},
	}
</script>

<style lang="scss">
	.pay-actionsheet {
		width: 100%;
		height: 100%;
		visibility: hidden;
		transform: translate3d(0, 100%, 0);
		transform-origin: center;
		transition: all 0.3s ease-in-out;
	}

	.pay-actionsheet-show {
		transform: translate3d(0, 0, 0);
		visibility: visible;
	}

	.pay-actionsheet-mask {
		background: rgba(0, 0, 0, 0.6);
		transition: all 0.3s ease-in-out;
		opacity: 0;
		visibility: hidden;
	}

	.pay-mask-show {
		opacity: 1;
		visibility: visible;
	}
</style>